import React, { useState } from 'react';
import {
  Form,
  Input,
  Select,
  Button,
  Upload,
  Modal,
  Space,
  message,
  InputNumber,
  Row,
  Col,
} from 'antd';
import {
  PlusOutlined,
  LinkOutlined,
  CloseOutlined,
} from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import type { CreatePostParams } from '../../types';
import './PostEditor.scss';

const { TextArea } = Input;
const { Option } = Select;

interface PostEditorProps {
  open: boolean;
  category: 'discussion' | 'help' | 'share' | 'trade';
  initialValues?: Partial<CreatePostParams>;
  onSubmit: (values: CreatePostParams) => Promise<void>;
  onCancel: () => void;
}

// 表单配置映射
const FORM_CONFIG = {
  discussion: {
    title: '发起讨论',
    contentPlaceholder: '分享你的想法、观点或问题，详细描述可以让大家更好地理解...',
    tagOptions: ['学习', '日常', '吐槽', '考试', '前端', '后端', '娱乐', '推荐'],
  },
  help: {
    title: '发布求助',
    contentPlaceholder: '详细描述你的问题，提供更多细节可以获得更好的帮助...',
    tagOptions: ['学习', '生活', '技术', '网络', '编程', '数据库', '前端', '后端'],
    helpTypes: ['学习求助', '生活求助', '技术求助'],
  },
  share: {
    title: '分享内容',
    contentPlaceholder: '分享你的资源、经验或发现，让更多人受益...',
    tagOptions: ['学习资料', '好东西', '风景', 'React', 'Python', 'APP', '美景', '推荐'],
    shareTypes: ['学习资料', '好东西', '风景', '经验分享'],
  },
  trade: {
    title: '发布商品',
    contentPlaceholder: '详细描述商品的状态、使用情况、配置信息等...',
    tagOptions: ['9成新', '8成新', '7成新', '无磕碰', '在保', '配件齐全', '功能正常', '品相好'],
    tradeCategories: ['电子产品', '生活用品', '图书资料', '体育用品', '其他'],
  },
};

const PostEditor: React.FC<PostEditorProps> = ({
  open,
  category,
  initialValues,
  onSubmit,
  onCancel,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [resourceLinks, setResourceLinks] = useState<string[]>(['']);

  const config = FORM_CONFIG[category];

  // 处理表单提交
  const handleSubmit = async (values: any) => {
    try {
      setLoading(true);

      // 构建统一的提交参数
      const postData: CreatePostParams = {
        title: values.title,
        content: values.content,
        category,
        tags: values.tags || [],
        images: fileList.map(file => file.url || file.response?.url || '').filter(Boolean),
      };

      // 根据分类添加特定字段
      if (category === 'help') {
        postData.helpType = values.helpType;
        postData.contact = values.contact;
        postData.requirements = values.requirements;
        postData.reward = values.reward;
      } else if (category === 'share') {
        postData.shareType = values.shareType;
        postData.downloadUrl = values.downloadUrl;
        postData.resourceLinks = resourceLinks.filter(link => link.trim() !== '');
      } else if (category === 'trade') {
        postData.price = values.price;
        postData.tradeCategory = values.tradeCategory;
      }

      await onSubmit(postData);
      message.success('发布成功！');
      form.resetFields();
      setFileList([]);
      setResourceLinks(['']);
      onCancel();
    } catch (error) {
      console.error('发布失败:', error);
      message.error('发布失败，请重试');
    } finally {
      setLoading(false);
    }
  };
  
  // 关闭弹窗时重置表单
  const handleCancel = () => {
    form.resetFields();
    setFileList([]);
    setResourceLinks(['']);
    onCancel();
  };

  // 处理图片上传
  const handleUploadChange = ({ fileList: newFileList }: any) => {
    setFileList(newFileList);
  };

  // 自定义上传
  const customUpload = ({ file, onSuccess }: any) => {
    setTimeout(() => {
      onSuccess({ url: URL.createObjectURL(file) }, file);
    }, 1000);
  };

  // 添加资源链接
  const addResourceLink = () => {
    setResourceLinks([...resourceLinks, '']);
  };

  // 删除资源链接
  const removeResourceLink = (index: number) => {
    const newLinks = resourceLinks.filter((_, i) => i !== index);
    setResourceLinks(newLinks.length > 0 ? newLinks : ['']);
  };

  // 更新资源链接
  const updateResourceLink = (index: number, value: string) => {
    const newLinks = [...resourceLinks];
    newLinks[index] = value;
    setResourceLinks(newLinks);
  };

  return (
    <Modal
      title={config.title}
      open={open}
      onCancel={handleCancel}
      width={1000}
      footer={null}
      destroyOnClose
      className="post-editor-modal"
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={initialValues}
        onFinish={handleSubmit}
      >
        <Row gutter={24}>
          {/* 左侧：公共字段 */}
          <Col span={12}>
            <div className="form-section">
              <h3 className="section-title">基本信息</h3>
              
              <Form.Item
                name="title"
                label="标题"
                rules={[
                  { required: true, message: '请输入标题' },
                  { min: 5, message: '标题至少5个字符' },
                  { max: 100, message: '标题最多100个字符' },
                ]}
              >
                <Input placeholder="请输入标题" />
              </Form.Item>

              <Form.Item
                name="content"
                label="内容"
                rules={[
                  { required: true, message: '请输入内容' },
                  { min: 10, message: '内容至少10个字符' },
                  { max: 2000, message: '内容最多2000个字符' },
                ]}
              >
                <TextArea
                  placeholder={config.contentPlaceholder}
                  rows={8}
                  showCount
                  maxLength={2000}
                />
              </Form.Item>

              <Form.Item
                name="tags"
                label="标签"
                rules={[
                  { required: true, message: '请至少选择一个标签' },
                ]}
              >
                <Select
                  mode="tags"
                  placeholder="选择或输入标签（最多5个）"
                  maxTagCount={5}
                >
                  {config.tagOptions.map(tag => (
                    <Option key={tag} value={tag}>{tag}</Option>
                  ))}
                </Select>
              </Form.Item>

              <Form.Item label="上传图片">
                <Upload
                  listType="picture-card"
                  fileList={fileList}
                  onChange={handleUploadChange}
                  customRequest={customUpload}
                  maxCount={9}
                  multiple
                >
                  {fileList.length < 9 && (
                    <div>
                      <PlusOutlined />
                      <div style={{ marginTop: 8 }}>上传</div>
                    </div>
                  )}
                </Upload>
                <div className="upload-tip">
                  支持jpg、png格式，单张≤5MB，最多9张
                </div>
              </Form.Item>
            </div>
          </Col>

          {/* 右侧：特定字段 */}
          <Col span={12}>
            <div className="form-section">
              <h3 className="section-title">
                {category === 'discussion' && '讨论设置'}
                {category === 'help' && '求助信息'}
                {category === 'share' && '分享信息'}
                {category === 'trade' && '商品信息'}
              </h3>

              {/* 求助区专用字段 */}
              {category === 'help' && (
                <>
                  <Form.Item
                    name="helpType"
                    label="求助类型"
                    rules={[{ required: true, message: '请选择求助类型' }]}
                  >
                    <Select placeholder="请选择求助类型">
                      {config.helpTypes?.map(type => (
                        <Option key={type} value={type}>{type}</Option>
                      ))}
                    </Select>
                  </Form.Item>

                  <Form.Item
                    name="contact"
                    label="联系方式"
                    rules={[{ required: true, message: '请输入联系方式' }]}
                  >
                    <Input placeholder="如：QQ号、微信号、邮箱等" />
                  </Form.Item>

                  <Form.Item name="requirements" label="要求/期望">
                    <TextArea
                      placeholder="说明你对帮助者的要求或期望"
                      rows={3}
                    />
                  </Form.Item>

                  <Form.Item name="reward" label="奖励/酬劳">
                    <Input placeholder="如：红包、请吃饭、无等" />
                  </Form.Item>
                </>
              )}

              {/* 分享区专用字段 */}
              {category === 'share' && (
                <>
                  <Form.Item
                    name="shareType"
                    label="分享类型"
                    rules={[{ required: true, message: '请选择分享类型' }]}
                  >
                    <Select placeholder="请选择分享类型">
                      {config.shareTypes?.map(type => (
                        <Option key={type} value={type}>{type}</Option>
                      ))}
                    </Select>
                  </Form.Item>

                  <Form.Item name="downloadUrl" label="下载地址">
                    <Input
                      prefix={<LinkOutlined />}
                      placeholder="如有资源下载地址，请填写"
                    />
                  </Form.Item>

                  <Form.Item label="相关链接">
                    <Space direction="vertical" style={{ width: '100%' }}>
                      {resourceLinks.map((link, index) => (
                        <Space key={index} style={{ width: '100%' }}>
                          <Input
                            prefix={<LinkOutlined />}
                            placeholder="输入相关资源链接"
                            value={link}
                            onChange={(e) => updateResourceLink(index, e.target.value)}
                            style={{ width: 300 }}
                          />
                          {resourceLinks.length > 1 && (
                            <Button
                              type="text"
                              danger
                              icon={<CloseOutlined />}
                              onClick={() => removeResourceLink(index)}
                            />
                          )}
                        </Space>
                      ))}
                      <Button
                        type="dashed"
                        onClick={addResourceLink}
                        icon={<PlusOutlined />}
                        block
                      >
                        添加链接
                      </Button>
                    </Space>
                  </Form.Item>
                </>
              )}

              {/* 交易区专用字段 */}
              {category === 'trade' && (
                <>
                  <Form.Item
                    name="tradeCategory"
                    label="商品分类"
                    rules={[{ required: true, message: '请选择商品分类' }]}
                  >
                    <Select placeholder="请选择商品分类">
                      {config.tradeCategories?.map(cat => (
                        <Option key={cat} value={cat}>{cat}</Option>
                      ))}
                    </Select>
                  </Form.Item>

                  <Form.Item
                    name="price"
                    label="价格"
                    rules={[
                      { required: true, message: '请输入价格' },
                      { type: 'number', min: 0, message: '价格不能为负数' },
                    ]}
                  >
                    <InputNumber
                      prefix="¥"
                      placeholder="请输入价格"
                      style={{ width: '100%' }}
                      min={0}
                      precision={2}
                    />
                  </Form.Item>
                </>
              )}

              {/* 讨论区提示 */}
              {category === 'discussion' && (
                <div className="tips-box">
                  <h4>发帖提示</h4>
                  <ul>
                    <li>发表友善、理性的观点</li>
                    <li>尊重他人的不同意见</li>
                    <li>避免发布广告信息</li>
                    <li>遵守社区规范</li>
                  </ul>
                </div>
              )}
            </div>
          </Col>
        </Row>

        <div className="form-footer">
          <Space size="middle">
            <Button onClick={handleCancel}>
              取消
            </Button>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
            >
              发布
            </Button>
          </Space>
        </div>
      </Form>
    </Modal>
  );
};

export default PostEditor;

